package ru.ksu.ktk.diploma.sdi.bean;

import org.richfaces.event.FileUploadListener;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import ru.ksu.ktk.diploma.sdi.dao.ResourcesDao;
import ru.ksu.ktk.diploma.sdi.model.DescriptionFile;
import ru.ksu.ktk.diploma.sdi.session.DescriptionList;
import ru.ksu.ktk.diploma.sdi.util.FacesUtils;
import ru.ksu.ktk.diploma.sdi.util.FileUtil;

import java.util.List;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

public class FileUploadBean extends BaseBean implements FileUploadListener {
    private ResourcesDao resourcesDao;
    /**
     * 
     */
    private static final long serialVersionUID = -6075324502603211867L;

    public void processUpload(UploadEvent event) {

        String sourceUri = getSourceUri();
        // TODO [coldflame]: this check fixes problem with twice method calls
        if (sourceUri != null){
            UploadItem uploadItem = event.getUploadItem();
            String fileName = FileUtil.getFileName(uploadItem.getFileName());
            resourcesDao.save(sourceUri, fileName, uploadItem.getFile());
            DescriptionFile newDescrFile = new DescriptionFile(fileName);
            saveDescriptionsInSession(newDescrFile);
        }
    }

    public String getSourceName() {

        return FacesUtils.getRequestParameter("sourceName");
    }

    public String getSourceUri() {
        return FacesUtils.getRequestParameter("sourceUri");
    }

    private void saveDescriptionsInSession(DescriptionFile newDescrFile) {
        getDescriptionList().addDescriptionFile(newDescrFile);
    }

    public ResourcesDao getResourcesDao() {
        return resourcesDao;
    }

    public void setResourcesDao(ResourcesDao resourcesDao) {
        this.resourcesDao = resourcesDao;
    }

}
